<?php
/**
 * Created by PhpStorm.
 * User: renyi
 * Date: 2017/10/13
 * Time: 下午17:22
 */

namespace App\Core;

use Closure;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Log;

/**
 * App\Core\BaseModel
 *
 * @mixin \Eloquent
 */
class BaseModel extends Model
{
    use CommonPoolMethod;

    protected $has_hash_id = false;

    public static function instance()
    {
        return new static();
    }

    public static function single($id, $member_name)
    {
        $ret = new Collection();

        $item = static::find($id);

        if (!empty($item))
        {
            $key   = $item->id;
            $value = "[".$item->id."].".$item->{$member_name};

            $ret->prepend($value, $key);
        }

        return $ret;
    }

    /**
     * 显示选项
     * mode = 'normal' 什么都不增加
     * mode = 'all' 增加全部的选项
     * mode = 'empty' 增加未选择的选项
     *
     * @param $member_name
     * @param string $mode
     * @param $callback
     * @return Collection
     */
    public static function selections($member_name, $mode = 'normal', Closure $callback = null)
    {
        $ret = new Collection();

        $query = new static();

        if ($callback instanceof \Closure)
        {
            //Log::info(static::class." in callback");
            $query = call_user_func($callback, $query);
        }
        else
        {
            //Log::info(static::class." in direct");
            $query = $query->orderBy('id', 'DESC');
        }

        $items = $query->get();

        foreach ($items as $item)
        {
            $key   = $item->id;
            $value = "[".$item->id."].".$item->{$member_name};

            $ret->prepend($value, $key);
        }

        if ($mode == 'all')
        {
            $ret->prepend("全部", 0);
        }
        else if ($mode == 'empty')
        {
            $ret->prepend("未选择", 0);
        }

        return $ret;
    }

    public static function get_id_by_hash_id($hash_id)
    {
        $ret = 0;

        if (!empty($hash_id) && $hash_id !== 0)
        {
            $obj = static::where("hash_id", $hash_id)->first();

            if (!empty($obj))
            {
                $ret = $obj->id;
            }
        }

        return $ret;
    }

    public static function get_object_by_hash_id($hash_id)
    {
        $ret = null;

        if (!empty($hash_id) && $hash_id !== 0)
        {
            $ret = static::where("hash_id", $hash_id)->first();
        }

        return $ret;
    }
}